/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vanniktech.emoji.sample;

import com.vanniktech.emoji.Actions.EmojIconActions;
import com.vanniktech.emoji.EmojiconRecentsManager;
import com.vanniktech.emoji.EmojiconTextField;
import com.vanniktech.emoji.EmojiconsPopup;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.multimodalinput.event.TouchEvent;

import java.util.Timer;
import java.util.TimerTask;

/**
 * CustomViewAbility
 *
 * @since 2021-06-28
 */
public class CustomViewAbility extends Ability implements Component.ClickedListener,
        Component.TouchEventListener {
    /**
     * 软键盘状态记录标签
     * 0 - 未弹出
     * -1 - 系统软键盘弹出
     * 1 - emoji自定义软键盘弹出
     */
    private int mKeyboardLabel = -1;

    /**
     * 防快速点击标记
     */
    private boolean isScenedClick = true;

    private String mTextStr;

    private Button mTriggerBtn;
    private EmojiconTextField mEditField;
    private StackLayout mEmojiLayout;
    private EmojIconActions mEmojiKeyboard;

    private EmojiconRecentsManager mRecentsManager;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_custom);

        initData();
        initView();
        initListener();
    }

    private void initData() {
        mRecentsManager = EmojiconRecentsManager.getInstance(getContext());
    }

    private void initView() {
        mTriggerBtn = (Button) findComponentById(ResourceTable.Id_custom_trigger_btn);
        mEditField = (EmojiconTextField) findComponentById(ResourceTable.Id_edit_field);
        mEditField.setTag(EmojiconsPopup.SET_TEXT_TAG);
        setCursorElement(mEditField, "#FFFF0000", 28);

        mEmojiLayout = (StackLayout) findComponentById(ResourceTable.Id_emoji_layout);

        mEmojiKeyboard = new EmojIconActions(this, mEmojiLayout, DirectionalLayout.LayoutConfig.MATCH_PARENT,
                850, mRecentsManager, mEditField);
    }

    private void initListener() {
        mTriggerBtn.setClickedListener(this);
        mEditField.setTouchEventListener(this);
        mEditField.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (mKeyboardLabel == -1) {
                    if (EmojiUtil.containsChar(s)) {
                        if (s.length() == 0) {
                            mEditField.setText("");
                            mTextStr = "";
                        } else {
                            mEditField.setText(mTextStr);
                        }
                    } else {
                        if (s.length() > 2) {
                            mEditField.setText(s.substring(s.length() - 2));
                        }
                        mTextStr = s;
                    }
                }
            }
        });
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_custom_trigger_btn:
                setBaseElement(mEditField, "#FF4081");
                if (mKeyboardLabel == 1) {
                    mEditField.setEnabled(true);
                    mEmojiKeyboard.hidePopup();
                    popUpKeyboard();
                    mKeyboardLabel = -1;
                    mTextStr = mEditField.getText();
                } else if (mKeyboardLabel == -1) {
                    mEditField.setEnabled(false);
                    mEmojiKeyboard.showPopup();
                    mEditField.clearFocus();
                    mKeyboardLabel = 1;
                } else {
                    mEditField.setEnabled(true);
                    mEmojiKeyboard.showPopup();
                    mKeyboardLabel = 1;
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                if (mKeyboardLabel == -1 || mKeyboardLabel == 0) {
                    setBaseElement(mEditField, "#FF4081");
                    mKeyboardLabel = -1;
                    mTextStr = mEditField.getText();
                }
                break;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        mKeyboardLabel = 0;
        if (isScenedClick) {
            isScenedClick = false;
            if (mEmojiKeyboard.getVisibility() == Component.VISIBLE) {
                mEmojiKeyboard.hidePopup();
                mEditField.setEnabled(true);
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isScenedClick = true;
                    }
                }, 1000);
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 弹出系统的软键盘
     */
    private void popUpKeyboard() {
        mEditField.setFocusable(Component.FOCUS_ENABLE);
        mEditField.setEnabled(true);
        mEditField.requestFocus();
        mEditField.simulateClick();
    }

    /**
     * 自定义光标
     *
     * @param textField 输入框
     * @param colorStr  颜色
     * @param height    高度
     */
    private void setCursorElement(TextField textField, String colorStr, float height) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.LINE); // 设置背景类型
        RgbColor rgbColor = RgbColor.fromArgbInt(Color.getIntColor(colorStr));
        shapeElement.setRgbColors(new RgbColor[]{rgbColor, rgbColor}); // 设置颜色值 起始与结束时的颜色
        shapeElement.setStroke(AttrHelper.vp2px(height, this), rgbColor); // 设置光标高度
        textField.setCursorElement(shapeElement); // 设置光标背景色
    }

    /**
     * 设置输入框的底线颜色
     *
     * @param textField 输入框
     * @param colorStr  颜色
     */
    private void setBaseElement(TextField textField, String colorStr) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor(colorStr)));
        textField.setBasement(shapeElement);
    }
}
